<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 持股人信息
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                        type="primary"
                        icon="el-icon-delete"
                        class="handle-del mr10"
                        @click="delAllSelection"
                >批量删除</el-button>
                <el-input v-model="query.name" placeholder="姓名" class="handle-input handle-input_min mr10"></el-input>
                <el-select v-model="query.nation" placeholder="民族" class="handle-select mr10"  >
                    <el-option key="1" label="请选择民族" value=""></el-option>
                    <el-option
                            v-for="(item,index) in nationList"
                            :key="index+'1'"
                            :value="item.name"
                            :label="item.name"
                    ></el-option>
                </el-select>
                <el-input v-model="query.address" placeholder="住址" class="handle-input handle-input_min mr10"></el-input>
                <el-select v-model="query.sex" placeholder="性别" class="handle-select mr10">
                    <el-option key="1" label="请选择性别" value=""></el-option>
                    <el-option key="2" label=" 男" value="0"></el-option>
                    <el-option key="3" label="女" value="1"></el-option>
                </el-select>
                <el-select v-model="query.education" placeholder="学历" class="handle-select mr10">
                    <el-option key="1" label="请选择学历" value=""></el-option>
                    <el-option key="2" label=" 学士" value="学士"></el-option>
                    <el-option key="3" label="硕士" value="硕士"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                    :data="tableData"
                    style="width: 100%"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="30" align="center" prop="pid"></el-table-column>
                <el-table-column prop="partnerName" label="姓名" width="200"  align="center" ></el-table-column>
                <el-table-column prop="a" label="年龄" align="center"></el-table-column>
                <el-table-column prop="nation" label="民族" align="center">
                </el-table-column>
                <el-table-column label="性别" align="center"> <!--prop="registerStatus"-->
                    <template slot-scope="scope">
                        <p v-if="scope.row.sex=='0'">男</p>
                        <p v-if="scope.row.sex=='1'">女</p>
                    </template>
                </el-table-column>
                <el-table-column prop="education" label="学历" align="center"></el-table-column>
                <el-table-column label="住址" align="center" prop="address"> <!--prop="registerStatus"-->
                </el-table-column>
                <el-table-column label="操作" width="300" align="center">
                    <template slot-scope="scope">
                        <el-button
                                style="color: #20a0ff"
                                    type="text"
                                    icon="el-icon-view"
                                    @click="toogleExpand(scope.$index,scope.row)"
                        >持股企业</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index,scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-lx-calendar"
                                class="red"
                                @click="handleDetail(scope.$index, scope.row)"
                        >详情</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 详情弹出框 -->
        <el-dialog title="详情" :visible.sync="detailVisible" width="50%">
             <el-form ref="form" :model="form" label-width="70px">
                 <el-form-item label="姓名">
                     <el-input v-model="form.partnerName" :disabled="true" readonly="readonly" ></el-input>
                 </el-form-item>
                 <el-form-item label="地址">
                     <el-input v-model="form.address" :disabled="true" readonly="readonly"></el-input>
                 </el-form-item>
                 <el-form-item label="民族">
                     <el-input v-model="form.nation" :disabled="true" readonly="readonly"></el-input>
                 </el-form-item>
                 <el-form-item label="性别">
                     <el-input v-if="form.sex=='1'" placeholder="女" :disabled="true" readonly="readonly"></el-input>
                     <el-input v-if="form.sex=='0'" placeholder="男" :disabled="true" readonly="readonly"></el-input>
                 </el-form-item>
                 <el-form-item label="学历">
                     <el-input v-model="form.education" :disabled="true" readonly="readonly"></el-input>
                 </el-form-item>
                 <el-form-item label="出生日期">
                     <el-input  :value="form.birthday | formatDate"  :disabled="true" readonly="readonly"></el-input>
                 </el-form-item>
                 <el-form-item label="党派">
                     <el-input v-model="form.organization" :disabled="true" readonly="readonly"></el-input>
                 </el-form-item>
                 <el-form-item v-if="form.oldName!=null" label="曾用名">
                     <el-input v-model="form.oldName" :disabled="true" readonly="readonly"></el-input>
                 </el-form-item>
                 <el-form-item v-if="form.englishName!=null" label="英文名">
                     <el-input v-model="form.englishName" :disabled="true" readonly="readonly"></el-input>
                 </el-form-item>
                 <el-form-item label="简介">
                     <el-input type="textarea" rows="5" v-model="form.briefIntroduction" :disabled="true" readonly="readonly"></el-input>
                 </el-form-item>
             </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailVisible = false" type="primary" style="margin-left: 100px">关闭</el-button>
            </span>
        </el-dialog>
        <!-- 编辑弹出框 -->
        <el-dialog title="修改" :visible.sync="editVisible" width="50%">
            <el-form :model="formPartner" :rules="formPartnerRules" ref="formPartner" label-width="80px" class="demo-ruleForm">
                <el-form-item label="姓名" required prop="partnerName">
                    <el-input v-model="formPartner.partnerName"></el-input>
                </el-form-item>
                <el-form-item label="地址" required prop="opstionAddress">
                    <area-cascader   v-model="formPartner.opstionAddress" :data="$pcaa" type="text" :level="1"></area-cascader>
                </el-form-item>
                <el-form-item label="民族" required prop="nation">
                    <!-- <el-input v-model="formPartner.nation" prop="partnerName"></el-input>-->
                    <el-select v-model="formPartner.nation" placeholder="民族" class="handle-select mr10"  >
                        <el-option  label="请选择民族" value=""></el-option>
                        <el-option
                                v-for="(item,index) in nationList"
                                :key="index+'1'"
                                :value="item.name"
                                :label="item.name"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" required prop="sex">
                    <el-select v-model="formPartner.sex" placeholder="性别" class="handle-select mr10">
                        <el-option key="1" label="请选择性别" value=""></el-option>
                        <el-option key="2" label=" 男" value="0"></el-option>
                        <el-option key="3" label="女" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="学历">
                    <el-select v-model="formPartner.education" placeholder="学历" class="handle-select mr10">
                        <el-option key="1" label="请选择学历" value=""></el-option>
                        <el-option key="2" label=" 学士" value="学士"></el-option>
                        <el-option key="3" label="硕士" value="硕士"></el-option>
                    </el-select>
                </el-form-item>
               <!-- <el-form-item label="出生日期" required prop="birthday">
                    <el-date-picker
                            v-model="formPartner.birthday"
                            align="right"
                            type="date"
                            placeholder="选择日期"
                            prop="birthday"
                            :picker-options="pickerOptions1">
                    </el-date-picker>
                </el-form-item>-->
                <el-form-item label="身份证号" required prop="identification">
                    <el-input v-model="formPartner.identification"  prop="identification"></el-input>
                </el-form-item>
                <el-form-item label="党派">
                    <el-select v-model="formPartner.organization" placeholder="党派" class="handle-select mr10">
                        <el-option key="1" label="请选择" value=""></el-option>
                        <el-option key="2" label="共产党" value="共产党"></el-option>
                        <el-option key="3" label="民建" value="民建"></el-option>
                        <el-option key="4" label="民盟" value="民盟"></el-option>
                        <el-option key="5" label="九三学社" value="九三学社"></el-option>
                        <el-option key="6" label="台盟" value="台盟"></el-option>
                        <el-option key="7" label="农工党" value="农工党"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item  label="曾用名">
                    <el-input v-model="formPartner.oldName"></el-input>
                </el-form-item>
                <el-form-item  label="英文名">
                    <el-input v-model="formPartner.englishName"></el-input>
                </el-form-item>
                <el-form-item label="简介" required prop="briefIntroduction">
                    <el-input type="textarea" rows="5" v-model="formPartner.briefIntroduction"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button  @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit('formPartner')">确定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="持股企业" :visible.sync="dialogTableVisible" width="88%">
            <el-table
                    :data="partnerInfoList"
                    border
                    class="table"
                    header-cell-class-name="table-header"
                    style="width: 100%">
                <el-table-column prop="a" label="公司" align="center"width="200"></el-table-column>
                <el-table-column prop="stockType" label="持股方式" align="center"width="150"></el-table-column>
                <el-table-column prop="stockPercent" label="出资比例(%)" align="center" width="150"></el-table-column>
                <el-table-column prop="realCapi" label="实缴出资额(万元)" align="center" width="180"></el-table-column>
                <el-table-column label="实缴时间" align="center" width="150">
                    <template slot-scope="scope">{{scope.row.capiDate | formatDate}}</template>
                </el-table-column>
                <el-table-column label="出资方式" align="center" prop="investName" width="150"></el-table-column>
                <el-table-column label="股份类型" align="center" prop="typeshares" width="180"></el-table-column>
                <el-table-column label="最终受益股份(%)" align="center" prop="finalBenefitPercent" width="150"></el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button  type="primary" @click="dialogTableVisible = false">关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {formatTimeToStr} from '../common/date.js';
    import Vue from 'vue';
    import { pcaa } from 'area-data-vue';
    import 'area-linkage-vue/dist/index.css';
    import AreaLinkageVue from 'area-linkage-vue';
    Vue.prototype.$pcaa = pcaa;
    Vue.use(AreaLinkageVue)
    export default {
        name: 'PartnerTable',
        data() {
            /**
             * 身份证号校验
             */
            var identi =(rule, value, callback) => {
                //身份证号的正则：/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
                const reg =/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;
                if (!value) {
                    return callback(new Error('身份证号不能为空'))
                }
                setTimeout(() => {
                    if (reg.test(value.trim())) {
                    //获取计算后出生日期
                    var birthDateStr = this.getBirthdayFromIdCard(value);

                    //获取当前的日期
                    var nowDateStr = this.getNowDate();
                    //获取计算后年龄(两个日期之间)
                    var age = this.getAge(birthDateStr, nowDateStr);
                    if(age >= 18){
                        callback()
                    }else {
                        callback(new Error('您为抵达合法年龄'))
                    }

                } else {
                    callback(new Error('请输入正确的身份证号'))
                }
            }, 100)
            }
            return {
                query: {
                    nation: '',
                    education: '',
                    sex:'',
                    address:'',
                    name: '',
                    pageIndex:0,
                    pageSize:7
                },
                tableData: [],
                partnerInfoList:[],
                multipleSelection: [],
                delList: [],
                editVisible: false,
                detailVisible:false,
                dialogTableVisible:false,
                pageTotal: 0,
                form: {},
                formPartner:{
                    pid:"",
                    partnerName: "",
                    address: "",
                    nation: "",
                    sex: "",
                    education: "",
                    birthday: "",
                    organization: "",
                    englishName: "",
                    oldName: "",
                    briefIntroduction:"",
                    identification:"",
                    b:""
                },
                formPartnerRules: {
                    partnerName: [
                        { required: true, message: '请输入法人名称', trigger: 'blur' },
                        { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ],
                    sex: [
                        { required: true, message: '请选择性别', trigger: 'change' }
                    ],
                    nation: [
                        { required: true, message: '请选择民族', trigger: 'change' }
                    ],
                    opstionAddress: [
                        { required: true, message: '请选择地址', trigger: 'change' }
                    ],
                    identification: [
                        {  required: true,validator:identi, message: '填写正确的身份证号', trigger: 'blur' }
                    ],
                    briefIntroduction:[
                        { required: true, message: '请输入个人简介', trigger: 'blur' }
                    ]
                },
                pickerOptions1: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    },
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }]
                },
                idx: -1,
                id: -1,
                nationList:{}

            };
        },
        created() {
            this.getNationList();
            this.getData(this.query);
        },
        methods: {
            // 获取 easy-mock 的模拟数据
            getData() {
                const _this = this;
                _this.$axios.post("/partner/partners",_this.query).then(res => {
                _this.tableData =res.data.data.partnerList;
                _this.pageTotal=res.data.data.totalCount;


            })
            },
            getNationList() {
                const _this = this;
                _this.$axios.get("/utils/nationList").then(res => {
                _this.nationList =res.data.data.data;


            });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 0);
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(()=>{
                    this.$axios.get("/partner/del/"+row.pid).then(res =>{
                    if(res.status = 200){
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                    this.getData();
                    }

              });
            }).catch(() => {});
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            delAllSelection() {
                const length = this.multipleSelection.length;
                let str = '';
                this.delList = this.delList.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].partnerName + ' ';
                    console.log(this.multipleSelection[i])
                    this.$axios.get("/partner/del/"+this.multipleSelection[i].pid).then(res =>{
                        if(res.status = 200){

                        this.multipleSelection = [];
                        this.tableData.splice(index, 1);

                    }

                });
                }
                this.$message.error(`删除了${length}条数据`);
                this.getData();
            },
            // 编辑操作
            handleEdit(index, row) {
                this.idx = index;
                this.$axios.get('/partner/'+ row.pid).then((res) => {
                    this.formPartner.opstionAddress=res.data.data.b;
                    this.formPartner=res.data.data;
            })
                this.editVisible = true;
            },
            //详情
            handleDetail(index, row) {
                const _this=this;
                _this.idx = index;
                this.$axios.get('/partner/' + row.pid).then((res) => {
                    _this.form=res.data.data;
            })
                this.detailVisible = true;
            },
            // 保存编辑
            saveEdit(formName) {
                const  _this =this;
                _this.$refs[formName].validate((valid) => {
                    if (valid) {
                        _this.formPartner.birthday=_this.getBirthdayFromIdCard( _this.formPartner.identification);
                        _this.formPartner.address = _this.formPartner.opstionAddress[1] + _this.formPartner.opstionAddress[2];
                        _this.formPartner.b= _this.formPartner.opstionAddress.toString();
                        console.log(_this.formPartner);
                        _this.$axios.post("/partner/saveEdit",_this.formPartner).then(res => {
                            this.getData();
                            _this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                            _this.$set(this.tableData, this.idx, this.formPartner);
                            _this.editVisible = false;
                    });
                    } else {
                        console.log('error submit!!');
                return false;
            }
            });
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                console.log(val)
                this.getData();
            },
            getBirthdayFromIdCard(idCard) {
                var birthday = "";
                if(idCard != null && idCard != ""){
                    if(idCard.length == 15){
                        birthday = "19"+idCard.substr(6,6);
                    } else if(idCard.length == 18){
                        birthday = idCard.substr(6,8);
                    }
                    birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
                }
                return birthday;
            },
            //获取当前日期
            getNowDate() {
                var d = new Date();
                var year = d.getFullYear();
                var month = d.getMonth() + 1;
                var day = d.getDate();
                var dateStr = year + '-' + this.getFormatDate(month) + '-' + this.getFormatDate(day);
                return dateStr;
            },
            //格式化日期的月份或天数的显示（小于10，在前面增加0）
            getFormatDate(value) {
                if (value == undefined || value == "") {
                    return '';
                }
                var str = value;
                if (parseInt(value) < 10) {
                    str = '0' + value;
                }
                return str;
            },
            //根据两个日期计算年龄（是否过生日）
            getAge(startDateStr, endDateStr)
            {
                //计算两个日期相差多少年
                var startDate = new Date(startDateStr);
                var endDate = new Date(endDateStr);
                var yearNum = endDate.getFullYear() - startDate.getFullYear();
                //获取两个日期（月+日）部分
                var sStr = startDateStr.substring(5, 10);
                var eStr = endDateStr.substring(5, 10);
                //判断两个日期大小
                //判断是否过生日
                if (new Date(sStr) <= new Date(eStr)) {
                    return yearNum + 1;
                }
                else {
                    return yearNum;
                }
            },
            toogleExpand(index, row) {
                const _this=this
                _this.idx = index;
                _this.$axios.get('/partnerinfo/byPidData/'+row.pid).then(res => {
                    if(res.data.flag){
                    _this.partnerInfoList= res.data.data;
                    _this.dialogTableVisible =true;
                }else{
                    _this.$message({
                        message: row.partnerName+'暂无入股企业',
                        type: 'warning'
                    });
                }

                    console.log(res);
            })
            }
            },
        filters: {
            formatDate: function (time) {
                if (time != null && time != "") {
                    var date = new Date(time);
                    return formatTimeToStr(date, "yyyy-MM-dd");
                } else {
                    return "";
                }
            }
        }


    };
</script>

<style scoped>

    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .handle-input_min{
        width: 150px;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>